package com.ssm.service;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SaveInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Map<String, List<String>> btnMap = ( Map<String, List<String>>)session.getAttribute("btnMap");
        //TODO 考虑超级管理员拥有所有权限，而不需要去授权


        //获取请求路径
        String path = request.getServletPath();//    /uc/addUser

        String strs[] = path.split("/");
        List<String> list = btnMap.get(strs[1]);
        if(list==null){
            list = new ArrayList<String>();
        }
        boolean flat = list.contains(strs[2]);
        if(flat){
            return true;
        }

        //处理响应时的中文乱码
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        response.getWriter().write("权限不足，请联系管理员");

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
